package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

//员工的业务层接口实现类
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //员工登录
    @Override
    public ResultInfo login(String username, String password) {
        //根据姓名查询用户信息
        Employee employee = employeeMapper.findByUsername(username);
        //判断用户是否存在
        if (employee == null) {
            return ResultInfo.error("用户不存在!");
        }
        //将传来的密码加密
        String md5Password = SecureUtil.md5(password);
        //与获取到的密码密文进行比较
        if (md5Password.equals(employee.getPassword())) {
            //判断登陆状态
            if (employee.getStatus() == 1) {
                //登陆成功
                return ResultInfo.success(employee);
            }
            //登录失败
            return ResultInfo.error("用户处于冻结状态,不能登录!");
        }
        //登陆失败
        return ResultInfo.error("密码输入错误!");
    }

    //根据员工姓名查询员工列表
    @Override
    public List<Employee> findByName(String name) {
        //调用mapper
        List<Employee> employees = employeeMapper.findByName(name);
        //返回结果
        return employees;
    }

    //新增员工
    @Override
    public void save(Employee employee) {
        //补全员工信息
        //a.生成员工id
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);
        //b.补全员工初始密码
        String password = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(password);
        //c.补全员工初始状态码
        employee.setStatus(1);
//        //d.补全创建人和创建时间
//        employee.setCreateUser(1L);// TODO: 2022/8/27
//        employee.setCreateTime(DateUtil.date());
//        //e.补全修改人和修改时间
//        employee.setUpdateUser(1L);// TODO: 2022/8/27
//        employee.setUpdateTime(DateUtil.date());
        //调用mapper新增员工
        employeeMapper.save(employee);
    }

    //回显员工
    @Override
    public Employee findById(Long id) {
        //调用mapper查询员工
        return employeeMapper.findById(id);
    }

    //修改员工
    @Override
    public void update(Employee employee) {
        //补全修改信息
//        employee.setUpdateTime(DateUtil.date());
//        employee.setUpdateUser(1L);// TODO: 2022/8/27
        //调用mapper
        employeeMapper.updateById(employee);
    }
}
